//
//  YYEHomeViewController.swift
//  weibo14
//
//  Created by mac on 16/3/2.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class YYEHomeViewController: YYEVisitorViewController {

    private let YYEStatausCellID = "YYEStatausCellID"
    // 当前控制器(view) 对应的视图模型
    lazy var statusListViewModel: YYEStatusListViewModel = YYEStatusListViewModel()
    
    override func viewDidLoad() {
        
        
        super.viewDidLoad()

        // 检查是否登陆
        if !userlogon {
        
            visitorView.setPageInfo(nil, message: nil)
            // 拿到访客视图
            return
        }
        
        // 添加导航栏上的item
        setupUI()
        setupTableView()
        loadData()
    }

    private func setupUI() {
    
      
        // 添加pullDownTipLabel到导航栏的下面
        self.navigationController!.view.insertSubview(pullDownTipLabel, belowSubview: navigationController!.navigationBar)
        // 设置pullDownTipLabel的Y值
        pullDownTipLabel.frame.origin.y = CGRectGetMaxY(navigationController!.navigationBar.frame) - pullDownTipLabel.frame.height
        
        tableView.tableFooterView = pullUpView

      
        tableView.addSubview(yyeRefreshControl)
        
        yyeRefreshControl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)

        
      navigationItem.leftBarButtonItem = UIBarButtonItem(imageNamed: "navigationbar_friendsearch", target: nil, action: nil)
        
      navigationItem.rightBarButtonItem = UIBarButtonItem(imageNamed: "navigationbar_pop",  target: self, action: "pushClick")
        
        
    }
    
    // 监听事件的方法
    @objc private func pushClick() {
        
        navigationController?.pushViewController(YYETempViewController(), animated: true)
        
        
        print("点击nav")
    }
    
    // 懒加载控件
    private lazy var pullUpView: UIActivityIndicatorView = {
    
        let v = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        
    
        v.color = UIColor.purpleColor()
        
        
        // v.startAnimating()
        return v
    }()
    
    private lazy var yyeRefreshControl: YYERefreshControl = YYERefreshControl()

    
    // MARK: - 加载数据
    
    
    @objc private func loadData(){
        
        statusListViewModel.loadData(pullUpView.isAnimating()) { (isSuccess, count) -> () in
            if isSuccess {
                
                print("本次加载了\(count)条数据")
                self.tableView.reloadData()

                if !self.pullUpView.isAnimating() {
                    // 显示下拉刷新的控件
                    self.showPullDownTipLabel(count)
                }

            }else{
                print("请求失败")
            }
            
            // 这里就可以结束刷新了刷新动画
            
            self.endRefresh()
        }
        
    }
    
    private func endRefresh(){
    
        pullUpView.stopAnimating()
        
        
       // refreshControl?.endRefreshing()
        
        
        self.yyeRefreshControl.endRefreshing()
    }
    
    // 下拉刷新提示的控件
    private lazy var pullDownTipLabel: UILabel = {
        let label = UILabel(textColor: UIColor.whiteColor(), fontSzie: 12)
        label.frame.size = CGSize(width: SCREENW, height: 35)
        label.backgroundColor = UIColor.orangeColor()
        label.hidden = true
        label.textAlignment = .Center
        return label
    }()

    private func showPullDownTipLabel(count: Int) {
        
        if pullDownTipLabel.hidden == false {
            // 如果是显示的,直接返回
            return
        }
        
        let countText = count == 0 ? "没有新的数据" : "加载了\(count)条数据"
        self.pullDownTipLabel.text = countText
        // 让其显示
        self.pullDownTipLabel.hidden = false
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.pullDownTipLabel.frame.origin.y += self.pullDownTipLabel.frame.height
            }) { (_) -> Void in
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    self.pullDownTipLabel.frame.origin.y -= self.pullDownTipLabel.frame.height
                    }, completion: { (_) -> Void in
                        self.pullDownTipLabel.hidden = true
                })
        }
    }
    
    // 设置tableView
    private func setupTableView(){
        tableView.registerClass(YYEStatusCell.self, forCellReuseIdentifier: YYEStatausCellID)
        // 因为cell高度随着内容高度变化而变化,那么就不能写死cell的高度
        // tableView.rowHeight = 250
        // 设置tableView的行高去自动计算
        tableView.rowHeight = UITableViewAutomaticDimension
        // 设置tableView的预估行高
        // 先让tableView能滚动起来,然后当有一个cell需要显示的话就去计算该cell的行高,并且调整tableView的滚动的范围,越精准越好
        tableView.estimatedRowHeight = 300
        
        // 隐藏tableView分割线
        tableView.separatorStyle = .None
        tableView.backgroundColor = UIColor(white: 239/255, alpha: 1)
        
    }
   
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
     //   if indexPath.row == statusListViewModel.statusArray!.count - 1 && pullUpView.isAnimating() == false {

        if (indexPath.row == ((statusListViewModel.statusArray?.count)! - 1) && pullUpView.isAnimating() == false) {
        
            self.pullUpView.startAnimating()
            // 2. 去加载数据
            print("去加载数据")
            self.loadData()
        
        }
    }
    

    // MARK: - Table view data source

    // 返回多少行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //        return self.statusArray?.count ?? 0
        return statusListViewModel.statusArray?.count ?? 0
    }

    // 返回cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 去缓存中取,如果没有取到,就帮我们创建一个cell返回
        let cell = tableView.dequeueReusableCellWithIdentifier(YYEStatausCellID, forIndexPath: indexPath) as! YYEStatusCell
        
        // 给cell设置视图模型
        cell.statusViewModel = statusListViewModel.statusArray![indexPath.row]
        // 给cell赋值
        //        cell.textLabel?.text = statusListViewModel.statusArray![indexPath.row].user?.screen_name
        return cell
    }

}
